package org.freelunch.visitors;

import java.io.IOException;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;

import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.BodyDeclaration;
import japa.parser.ast.body.ClassOrInterfaceDeclaration;
import japa.parser.ast.body.TypeDeclaration;
import japa.parser.ast.type.ClassOrInterfaceType;

public class ClassVisitor {

	public static void visit(CompilationUnit cu,IndexWriter indexWriter, String location) throws CorruptIndexException, IOException {
		
		if(cu.getTypes()!=null)
		for (TypeDeclaration td:cu.getTypes())
				{
					if(td instanceof ClassOrInterfaceDeclaration)
					{
						if(((ClassOrInterfaceDeclaration) td).isInterface())
								continue; //fuh-get interfaces ..they are nothing but cosmetic 4me:)
						
						Document doc = new Document();
						
						doc.add(new Field("Package",cu.getPackage().toString(),Field.Store.YES,Field.Index.NOT_ANALYZED));
						doc.add(new Field("Name",td.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));
						doc.add(new Field("Location",location,Field.Store.YES,Field.Index.NOT_ANALYZED));
						String implement="";
						if(((ClassOrInterfaceDeclaration) td).getImplements()!=null)
						{for( ClassOrInterfaceType cot :((ClassOrInterfaceDeclaration) td).getImplements())
						{
							implement=implement+cot.getName()+",";
							
						}
						implement=implement.length()>0?implement.substring(0,implement.length()-1):"";
						doc.add(new Field("Implements",implement,Field.Store.YES,Field.Index.NOT_ANALYZED));
						}String extend="";
						if((ClassOrInterfaceDeclaration)td!=null)
						{	
							List<ClassOrInterfaceType> list=((ClassOrInterfaceDeclaration) td).getExtends();
							if(list!=null){
									for( ClassOrInterfaceType cot :list)
										{
											extend=extend+cot.getName()+",";
							
										}
						extend=extend.length()>0?extend.substring(0,extend.length()-1):"";
						doc.add(new Field("Extends",implement,Field.Store.YES,Field.Index.NOT_ANALYZED));}
						}
						indexWriter.addDocument(doc);
						indexWriter.commit();
						
						
						
					}
			
			
				}
		
		
		
		
			
		
	}

}
